#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
void Usage(std::string proc)
{
    std::cout << "\r\nUsage: " << proc << "port[1024+]\n"
              << std::endl;
}
//./tcpclient serverio serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    // 栈上更新sockaddr_in结构体数据
    std::string serverip = argv[1]; // 字符串类型
    uint16_t serverport = std::stoi(argv[2]);
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_pton(AF_INET, serverip.c_str(), &(server.sin_addr));

    while (true)
    {
        int isreconnect = false;
        int cnt = 5;
        int sockfd = 0;
        sockfd = socket(AF_INET, SOCK_STREAM, 0); // 创建TCP协议的套接字，此时还不知道服务端是谁
        if (sockfd < 0)
        {
            std::cerr << "socket error" << std::endl;
            return 1;
        }
        do
        {
            int n = connect(sockfd, (struct sockaddr *)&server, sizeof(server)); // 通过server的结构体连接服务端
            if (n < 0)                                                           // 如果失败就重连
            {
                isreconnect = true;
                cnt--;
                std::cerr << "connect error...,recnonect:" << cnt << std::endl;
                sleep(1);
            }
            else
            {
                break; // 只要有一次连接成功就不需要重连，break后继续向下执行
            }
        } while (cnt && isreconnect);
        if (cnt == 0) // 重连了5次，证明connect接口这里连接失败了5次，isreconnect一直是true，但是cnt一直减减，
        // 认为用户连接失败
        {
            std::cerr << "user offonline..." << std::endl;
            break;
        }
        while (true)
        {
            std::string message;
            std::cout << "Please Enter# ";
            std::getline(std::cin, message);
            int n1 = write(sockfd, message.c_str(), message.size()); // 向服务端发送数据
            if (n1 < 0)
            {
                isreconnect = true;
                std::cerr << "write error..." << std::endl;
                break;
            }
            char inbuffer[4096];
            int n = read(sockfd, inbuffer, sizeof(inbuffer)); // 读取服务端返回的数据
            if (n > 0)
            {
                inbuffer[n] = 0;
                std::cout << inbuffer << std::endl;
            }
            else
            {
                break;
            }
        }
        close(sockfd);
    }

    return 0;
}